#include "Image.h"
#include <QColor>
#include <QRgb>
#include <QFile>
#include <QtOpenGL/QGLWidget>
#include <QImageReader>

Image::Image(QString name)
{
    Load(name);
}
Image::Image()
{
}

Image::~Image()
{
    if(glIsTexture(m_texture)) glDeleteTextures(1, &m_texture);
}

void Image::Load(QString name)
{
    QImage image;
    //image.createMaskFromColor(qRgb(255, 0, 255), Qt::MaskOutColor);
    image = image.createMaskFromColor(qRgb(255, 0, 255), Qt::MaskOutColor);
    image.load(name);
    //image = image.createMaskFromColor(qRgb(255, 0, 255));
    image = QGLWidget::convertToGLFormat(image);

    for(int i = 0; i < image.width(); ++i)
    {
        for(int j = 0; j < image.height(); ++j)
        {
            if(image.pixel(i, j) == qRgb(255, 0, 255))
                image.setPixel(i, j, qRgba(170, 170, 170, 0));  // ARRGGGGG
        }
    }


    glEnable(GL_BLEND);
    glGenTextures(1, &m_texture);

    glBindTexture(GL_TEXTURE_2D, m_texture);

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);

    glTexImage2D(GL_TEXTURE_2D,0,4,image.width(),image.height(),0, GL_RGBA, GL_UNSIGNED_BYTE, image.bits());

    myPos.x = 0; myPos.y = 0;
    myClip.x = 0; myClip.y = 0; myClip.w = image.width(); myClip.h = image.height();

    myWidth = image.width();
    myHeight = image.height();

}

int Image::GetX() const
{
    return myPos.x;
}

int Image::GetY() const
{
    return myPos.y;
}

Rect Image::GetClipRect(){
    return myClip;
}

void Image::Render(int x, int y)
{
    float width = static_cast<float>(myClip.w);
    float height = static_cast<float>(myClip.h);

    float left = static_cast<float>(myClip.x);
    float top = static_cast<float>(myClip.y);

    float right = static_cast<float>(myClip.x + myClip.w);
    float bottom = static_cast<float>(myClip.y + myClip.h);

    //std::swap(left, right);
    std::swap(top, bottom);

    glPushMatrix();
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, m_texture);

    glTranslatef(myPos.x + x, myPos.y + y, 0);

    /// idk if the setClip function works ARRG
    glBegin(GL_TRIANGLE_STRIP);

        glTexCoord2f(left / myWidth, top / myHeight);
        glVertex2f(0, 0);

        glTexCoord2f(right / myWidth , top / myHeight);
        glVertex2f(width, 0);

        glTexCoord2f(left / myWidth, bottom / myHeight);
        glVertex2f(0, height);


        glTexCoord2f(right / myWidth, bottom/ myHeight);
        glVertex2f(width, height);



    glEnd();

    glPopMatrix();

}

